<!-- 事件日志 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset">
        <el-cascader
        :options="options"
        @change="handleChange"></el-cascader>
      </connsearch>
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;"  @tab-click="tabClick">
          <el-tab-pane label="显示日统计趋势" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart :chartData="barchartData" @barclick="echartsClick" title="显示日统计趋势"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="访问用户统计分析" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart  :chartData="pie1Data" @pieclick="echartsClick" title="访问用户统计分析"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="异常域名统计分析" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <piechart :chartData="pie2Data" @pieclick="echartsClick" title="异常域名统计分析"/>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin:16px 0;">
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="发生时间" prop="TransTime" width="160px" align="left"></el-table-column>
          <el-table-column label="发生终端" prop="EmployeeName" width="160px"  align="left">
            <template slot-scope="{row}">
              {{ row.Name || '--' }}
            </template>
          </el-table-column>
          <!-- -{{ row.DepartmentName || '-' }} -->
          <el-table-column label="终端地址" prop="FromIP" width="160px"  align="left"></el-table-column>
          <!-- <el-table-column label="事件原因" prop="EventID" width="160px"  align="left">
            <template slot-scope="{row}">
              {{ row.EventID === '800' ? '访问告警域名' : (row.EventID === '801' ? '访问禁止域名' : '未知[0]') }}
            </template>
          </el-table-column> -->
          <el-table-column label="描述信息" prop="URL" align="left"></el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import { getNowDay, parseTime } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
export default {
  components: { connsearch, barchart, piechart },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle: '显示日统计趋势',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      barchartData: {xAxis:[],series:[]},
      pie1Data: [],
      pie2Data: [],
      tableData:[],
      searchform:{},
      options:{},
      searchobj: {},
      formOptions: [
        {
          col: 8,
          hidden: false,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          initValue: [], // 字段初始值,
          element: "el-date-picker", // 指定elementui组件
          type: "", // 日期选择类型,
          events: {
            input(val) {
              that.searchform.timeRange = val
            },
          },
        },
        {
          col: 4,
          hidden: false,
          label: "统计排名", // label文字
          prop: "SumCount", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 10, // 字段初始值,
          placeholder: "请选择统计排名", // elementui组件属性
          options: [
            { label: '前十名', value: 10 },
            { label: '前二十名', value: 20 },
            { label: '前三十名', value: 30 }
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.SumCount = val
            },
          },
        },
        {
          col: 4,
          label: "终端用户",
          prop:"Name",
          element: "el-cascader",
          initValue: "",
          placeholder: "请选择终端用户",
          options:[],
          checkStrictly: false,
          events: {
            input(val) {
              that.searchform.Name = val
            },
          },
        },
        {
          col: 8,
          label: "描述信息", // label文字
          prop: "Descp", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入描述信息,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Descp = val
            },
          },
        },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
    let arr = [ parseTime(startTime), '']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    this.$set(this.searchform,'SumCount', 10)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.GetDepartment()
  },
  methods: {
    handleChange(){},
    // 获取所有数据
    getData(){
      this.GetEventLog()
      switch (this.tabTitle) {
        case '显示日统计趋势':
          this.GetEventLogSumGroupByDate()
          break;
        case '访问用户统计分析':
          this.GetEventLogSumGroupByUser()
          break;
        default:
          this.GetEventLogSumGroupByDescp()
          break;
      }
    },
    echartsClick(val,title){
      this.pageNum = 1
      if(title === '显示日统计趋势'){
        this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
        this.GetEventLog(this.searchobj)
      }else if(title === '访问用户统计分析'){
        this.searchobj = { Name: val }
        this.GetEventLog(this.searchobj)
      }else{
        this.searchobj = { Descp: val }
        this.GetEventLog(this.searchobj)
      }
      // this.GetEventLog()
    },
    tabClick(row){
      this.tabTitle = row.label
      switch (row.label) {
        case '显示日统计趋势':
          this.GetEventLogSumGroupByDate()
          break;
        case '访问用户统计分析':
          this.GetEventLogSumGroupByUser()
          break;
        default:
          this.GetEventLogSumGroupByDescp()
          break;
      }
    },
    // 获取部门和终端用户
    async GetDepartment(){
      const departments = await connrequest('GetDepartment')
      const employees = await connrequest('GetEmployee')
      departments.Data.map(item => {
        item.SubClass = item.DepartmentName
      })
      employees.Data.map(item => {
        item.SubClass = item.Name
        item.ParentID = item.DID
      })
      this.getnewarr(departments.Data, employees.Data)
    },
    getnewarr(departments, employees){
      const newDepartmentArray = [];
      //遍历departments数组
      departments.forEach(department => {
        //新建一个对象，用于存储合并后的数据
        const newDepartmentObj = {
            DepartmentName: department.DepartmentName,
            SubClass: department.DepartmentName,
            ParentName: department.ParentName,
            ID: department.ID,
            ParentID: department.ParentID,
            children: []
        };
        //遍历employees数组
        employees.forEach(employee => {
          //如果employee的Department和department的DepartmentName相同
          if (employee.Department === department.DepartmentName) {
            //将该employee对象添加到newDepartmentObj的children数组中
            newDepartmentObj.children.push(employee);
          }
        });
        //将newDepartmentObj添加到newDepartmentArray数组中
        newDepartmentArray.push(newDepartmentObj);
      });
      const convertedArray = this.convertArray(newDepartmentArray);
      this.formOptions.map( item => {
        if(item.label === '终端用户'){
          item.options = convertedArray
        }
      })
    },
    convertArray(data) {
      const map = {};
      const result = [];
      data.forEach(item => {
        if(!item.children){
          item.children = [];
        }
        map[item.ID] = item;
      });
      data.forEach(item => {
        if (item.ParentID !== 0) {
          const parent = map[item.ParentID];
          parent.children.push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : '',
          Descp: this.searchform.Descp || '',
          TransDate: '',
          SumCount: this.searchform.SumCount || 10,
          ...searchobj
        }
      }
      const res = await connrequest('GetEventLog', data)
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    // 获取事件用户统计
    async GetEventLogSumGroupByUser(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : '',
          Descp: this.searchform.Descp || '',
          SumCount: this.searchform.SumCount || 10,
        }
      }
      const res = await connrequest('GetEventLogSumGroupByUser', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie1Data = arr
    },
    // 获取事件域名统计
    async GetEventLogSumGroupByDescp(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : '',
          Descp: this.searchform.Descp || '',
          SumCount: this.searchform.SumCount || 10,
        }
      }
      const res = await connrequest('GetEventLogSumGroupByDescp', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        arr.push({name: item.Name, value: item.Count})
      })
      this.pie2Data = arr
    },
    // 获取事件日期统计
    async GetEventLogSumGroupByDate(){
      let xAxis = []
      let series= []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : '',
          Descp: this.searchform.Descp || '',
          SumCount: this.searchform.SumCount || 10,
        }
      }
      const res = await connrequest('GetEventLogSumGroupByDate', data)
      res.Data = res.Data || []
      res.Data.map( item =>{
        xAxis.push(item.Name)
        series.push(item.Count)
      })
      this.barchartData = {xAxis,series}
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchform = {...val}
      if(this.searchform.timeRange){
        this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData()
    },
    // 重置
    reset(){
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "统计排名"){
          item.initValue = 10
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$set(this.searchform,'SumCount', 10)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog(this.searchobj)
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetEventLog(this.searchobj)
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>